
import { Fragment, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { Modal, Button, Avatar, message } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

import {
    border_line,
    img_clip_wrap,
    img_preview_wrap,
    upload_clip,
    upload_clip_tip,
    upload_clip_img,
    update_btn,
    img_preview_tip,
} from './index.module.css'
import './index.css'

import { postUpdateAvator, postUpdateGroupAvator } from '../../assets/js/api'
import {
    changeUserInfo,
    changeCurrentRoomInfo
} from '../../store/actions'
import {
    imgUrlDev,
    getToken,
    setToken,
} from '../../assets/js/tools'
import { publish, subscribe, unsubscribe } from 'pubsub-js';
import { showAvatorUpload, showGroupInfo } from '../../event-type';


function AvatorUpload(props) {

    const { user, changeUserInfo, currentRoomInfo, changeCurrentRoomInfo } = props;


    const [visible, setVisible] = useState(false);
    const [imageUrl, setImageUrl] = useState('');
    const [newImageUrl, setNewImageUrl] = useState('');
    const [loading, setLoading] = useState(false);
    const [uploadFile, setLoadFile] = useState(null);
    const [operateType, setOperateType] = useState({});

    useEffect(() => {
        subscribe(showAvatorUpload, (event, data) => {
            setOperateType(data.type);
            // 每次更新框消失将数据复原初始
            setVisible(true);
            setImageUrl(data.type === 'user' ? user.avator : currentRoomInfo.group_avator);
            setNewImageUrl('');
            setLoading(false);
        });
        return () => {
            unsubscribe(showAvatorUpload);
        }
    }, [currentRoomInfo, user]);
    

    function getBase64(img, callback) {
        // 更新图片路径处理
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }
    function beforeUpload(file) {
        // 限定图片类型和大小
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('上传图片类型必须为jpg或png！');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          message.error('图片大小不能超过2MB!');
        }
        return isJpgOrPng && isLt2M;
    }
    function handleChange(e) {
        // 选中图片后将其预览显示
        const file = e.target.files[0];
        if (!beforeUpload(file)) return;
        setLoading(true);
        getBase64(file, imageUrl => {
            setLoadFile(file)
            setLoading(false);
            setImageUrl(imageUrl);
            setNewImageUrl(imageUrl);
        });
    }
    function commitUpdate() {
        // pan duan 使用哪个提交路径
        if (operateType === 'user') updateUserAvator();
        else if (operateType === 'group') updateGroupAvator();
    }
    function updateUserAvator() {
        // 确定更新头像图片
        const uploading = message.loading('上传中。。。');
        const avatorFileData = new FormData();
        avatorFileData.append('file', uploadFile);
        avatorFileData.append('id', user.id);

        postUpdateAvator(avatorFileData)
        .then(res => {
            const { code, message: content, data, token } = res.data;
            const type = code === 1 ? 'success' : 'error';
            // 更新数据
            if (code === 1) {
                changeUserInfo(data);
                if (getToken('token')) {
                    setToken('token', token);
                }
            }
            message.open({type, content});

            uploading();
            setVisible(false);
        })
        .catch(err => {
            console.log(err)
        });
    }
    function updateGroupAvator() {
        // 确定更新头像图片
        const uploading = message.loading('上传中。。。');
        const avatorFileData = new FormData();
        avatorFileData.append('file', uploadFile);
        avatorFileData.append('group_id', currentRoomInfo.group_id);
        postUpdateGroupAvator(avatorFileData)
        .then(res => {
            const { code, message: content, data } = res.data;
            const type = code === 1 ? 'success' : 'error';
            // 更新数据
            if (code === 1) {
                changeCurrentRoomInfo(data);
            }
            message.open({type, content});
            publish(showGroupInfo, data);

            uploading();
            setVisible(false);
        })
        .catch(err => {
            console.log(err)
        });
    }


    return (
        <Modal 
            className="upload_wrapper"
            title="更换头像"
            visible={visible}
            maskClosable={false}
            centered={true}
            width={720}
            zIndex={1001}
            style={{width: '740px', }}
            bodyStyle={{width: '720px', height: '340px', lineHeight: '340px', display: 'flex', alignItems: 'center', justifyContent: 'center'}}
            footer={<Button type="primary" className={update_btn} onClick={commitUpdate}>更新</Button>}
            onCancel={() => setVisible(false)}>
            <div className={img_clip_wrap}>
                <label className={upload_clip} htmlFor="input_file">
                    {
                        newImageUrl ?
                            <img className={upload_clip_img} src={newImageUrl} alt="" /> : 
                            loading ? 
                                <LoadingOutlined style={{fontSize: '18px'}} /> :
                                <Fragment>
                                    <PlusOutlined style={{fontSize: '18px'}} />
                                    <div className={upload_clip_tip}>选择图片</div>
                                </Fragment>
                    }
                </label>
                <input type="file" id="input_file"
                    accept="image/png,image/jpg,image/jpeg" 
                    style={{display: 'inline-block', opacity: 0, width: 0, height: 0}}
                    onChange={handleChange}
                />
            </div>
            <div className={border_line}></div>
            <div className={img_preview_wrap}>
                <Avatar src={newImageUrl ? imageUrl : imgUrlDev(imageUrl)} size={160} />
                <span className={img_preview_tip}>
                    {
                        newImageUrl ? '预览头像' : '当前头像'
                    }
                </span>
            </div>
        </Modal>
    )
}


function mapStateToProps(state) {
    return {
        user: state.user,
        currentRoomInfo: state.currentRoomInfo
    }
}
export default connect(
    mapStateToProps,
    {
        changeUserInfo,
        changeCurrentRoomInfo
    }
)(AvatorUpload);
